package com.schoolegard.services.impl;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.axis2.AxisFault;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.schoolegard.services.SchoolDataService;
import com.schoolgard.dao.MsgReceiverDao;
import com.schoolgard.dao.SchoolDataDao;
import com.schoolgard.entitybean.GridDataModel;
import com.schoolgard.entitybean.MsgReceiver;
import com.schoolgard.entitybean.SchoolData;
import com.tecsun.business.extra.centralauthenticate.yunwei.bean.ArrayOfSchoolDataBean;
import com.tecsun.business.extra.centralauthenticate.yunwei.bean.ArrayOfUserDataBean;
import com.tecsun.business.extra.centralauthenticate.yunwei.bean.DataInterfaceBean;
import com.tecsun.business.extra.centralauthenticate.yunwei.bean.DataServiceInterfaceBeanResponse;
import com.tecsun.business.extra.centralauthenticate.yunwei.bean.SchoolDataBean;
import com.tecsun.business.extra.centralauthenticate.yunwei.bean.UserDataBean;
import com.tecsun.business.extra.centralauthenticate.yunwei.yunweiservice.GetSchoolInfo;
import com.tecsun.business.extra.centralauthenticate.yunwei.yunweiservice.GetSchoolInfoResponse;
import com.tecsun.business.extra.centralauthenticate.yunwei.yunweiservice.GetUserInfo;
import com.tecsun.business.extra.centralauthenticate.yunwei.yunweiservice.GetUserInfoResponse;
import com.tecsun.business.extra.centralauthenticate.yunwei.yunweiservice.YunWeiDataServiceInterfaces;
import com.tecsun.business.extra.centralauthenticate.yunwei.yunweiservice.YunWeiDataServiceInterfacesStub;

public class SchoolDataServiceImpl implements SchoolDataService {
	
	private SchoolDataDao schoolDataDao;
	
	private MsgReceiverDao msgReceiverDao;

	public void setSchoolDataDao(SchoolDataDao schoolDataDao) {
		this.schoolDataDao = schoolDataDao;
	}

	public void setMsgReceiverDao(MsgReceiverDao msgReceiverDao) {
		this.msgReceiverDao = msgReceiverDao;
	}

	@Override
	public GridDataModel<SchoolData> find4Page(SchoolData schoolData, int first, int max) {
		DetachedCriteria criteria = DetachedCriteria.forClass(SchoolData.class);
		if(schoolData != null) {
			if(schoolData.getName() != null) {
				criteria.add(Restrictions.eq("name", schoolData.getName()));
			}
		}
		List<SchoolData> list = schoolDataDao.findByCriteria(criteria, first, max);
		int total = schoolDataDao.getRowCount(criteria);
		GridDataModel<SchoolData> page = new GridDataModel<SchoolData>();
		page.setPage(first / max + 1);
		page.setRows(list);
		page.setTotal(total);
		return page;
	}

	@Override
	public void addReceiver(MsgReceiver msgReceiver) {
		try{
			msgReceiverDao.createOrModify(msgReceiver);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void deleteReceiver(Long id) {
		msgReceiverDao.remove(findById(id));
	}

	@Override
	public GridDataModel<MsgReceiver> findReceiverBySchoolId(Long id, int first,int max) {
		DetachedCriteria criteria = DetachedCriteria.forClass(MsgReceiver.class);
		if(id != null && id > 0) {
			criteria.add(Restrictions.eq("schoolId", id));
		}
		criteria.addOrder(Order.asc("type"));
		criteria.addOrder(Order.desc("id"));
		
		List<MsgReceiver> list = msgReceiverDao.findByCriteria(criteria, first, max);
		int total = msgReceiverDao.getRowCount(criteria);
		GridDataModel<MsgReceiver> page = new GridDataModel<MsgReceiver>();
		page.setPage(first / max + 1);
		page.setRows(list);
		page.setTotal(total);
		return page;
	}

	@Override
	public MsgReceiver findById(Long id) {
		return msgReceiverDao.findById(id);
	}

	@Override
	public boolean updateStatus(Long id, Integer status) {
		MsgReceiver mr = findById(id);
		if(mr != null) {
			mr.setStatus(status);
			msgReceiverDao.modify(mr);
			return true;
		}
		return false;
	}

	@Override
	public int findSysReceiverEnable(Long schoolId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(MsgReceiver.class);
		if(schoolId != null && schoolId > 0) {
			criteria.add(Restrictions.eq("schoolId", schoolId));
			criteria.add(Restrictions.eq("status", 1));
			criteria.add(Restrictions.eq("type", 0));
		}else{
			return 0;
		}
		return msgReceiverDao.getRowCount(criteria);
	}

	@Override
	public String addSchoolData(SchoolData schoolData) {
		try{
			schoolDataDao.create(schoolData);
		}catch(Exception e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}

	@Override
	public String updateSchoolData(SchoolData schoolData) {
		try{
			schoolDataDao.modify(schoolData);
		}catch(Exception e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}

	@Override
	public String deleteSchoolData(Long schoolId) {
		if(schoolId != null && schoolId > 0) {
			SchoolData schoolData = schoolDataDao.findById(schoolId);
			if(schoolData != null) {
				try{
					schoolDataDao.remove(schoolData);
					return "1";
				}catch(Exception e) {
					e.printStackTrace();
					return "0";
				}
			}
		}
		return "0";
	}

	@Override
	public List<MsgReceiver> findReceiverListBySchoolId(Long id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(MsgReceiver.class);
		if(id != null && id > 0) {
			criteria.add(Restrictions.eq("schoolId", id));
		}
		criteria.addOrder(Order.asc("type"));
		criteria.addOrder(Order.desc("id"));
		
		return msgReceiverDao.findByCriteria(criteria);
		
	}
	private List<MsgReceiver> findReceiverListBySys(Long id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(MsgReceiver.class);
		if(id != null && id > 0) {
			criteria.add(Restrictions.eq("schoolId", id));
			criteria.add(Restrictions.eq("type", 0));
		}else{
			return new ArrayList<MsgReceiver>();
		}
		return msgReceiverDao.findByCriteria(criteria);
		
	}
	
	public MsgReceiver findReceiverByPersonId(String id, Long SchoolId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(MsgReceiver.class);
		if(id != null && id.length() > 0) {
			criteria.add(Restrictions.eq("personId", id));
			criteria.add(Restrictions.eq("schoolId", id));
		}
		List<MsgReceiver> list = msgReceiverDao.findByCriteria(criteria);
		if(list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	public void deleteOld(Long id,UserDataBean[] dataBean ) {
		List<MsgReceiver> receiver = findReceiverListBySys(id);
		if(receiver == null || receiver.size() == 0) {
			return;
		} 
		boolean flag = true;
		for(MsgReceiver rece : receiver) {
			for(UserDataBean userBean : dataBean){
				if(rece.getPersonId().equals(userBean.getUserid())) {
					flag = false;
				}
			}
			if(flag) {
				msgReceiverDao.remove(rece);
			}
		}
	}
	public void findRemoteDate(Long id){
		try {
			YunWeiDataServiceInterfaces interfaces = new YunWeiDataServiceInterfacesStub();
			GetUserInfo getUserInfo = new GetUserInfo();
			DataInterfaceBean param = new DataInterfaceBean();
			param.setAuthkey("123456");
			param.setCurrentPage(0);
			param.setPageSize(Integer.MAX_VALUE);
			param.setSchoolid(id.longValue());
			getUserInfo.setIn0(param);
			GetUserInfoResponse response = interfaces.getUserInfo(getUserInfo);
			
			DataServiceInterfaceBeanResponse beanResponse =  response.getOut();
			ArrayOfUserDataBean bean = beanResponse.getUserList();
			if(bean != null) {
				UserDataBean[] dataBean = bean.getUserDataBean();
				if(dataBean != null && dataBean.length > 0) {
					for(UserDataBean userBean : dataBean){
						MsgReceiver rece = findReceiverByPersonId(userBean.getUserid(),id);
						if(rece == null) {
							rece = new MsgReceiver();
							rece.setStatus(1);
						}
						rece.setName(userBean.getLogin_name());
						rece.setPersonId(userBean.getUserid());
						rece.setPhone(userBean.getPhone());
						rece.setSchoolId(id);
						rece.setType(0);
						addReceiver(rece);
					}
					deleteOld(id,dataBean);
				}
			}

		} catch (AxisFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void updateSchool(){
		try {
			YunWeiDataServiceInterfaces interfaces = new YunWeiDataServiceInterfacesStub();
			GetSchoolInfo getSchoolInfo = new GetSchoolInfo();
			DataInterfaceBean param = new DataInterfaceBean();
			param.setAuthkey("123456");
			param.setCurrentPage(0);
			param.setPageSize(Integer.MAX_VALUE);
			getSchoolInfo.setIn0(param);
			GetSchoolInfoResponse response = interfaces.getSchoolInfo(getSchoolInfo);
			
			DataServiceInterfaceBeanResponse beanResponse =  response.getOut();
			ArrayOfSchoolDataBean bean = beanResponse.getSchoolList();
			if(bean != null) {
				SchoolDataBean[] dataBean = bean.getSchoolDataBean();
				if(dataBean != null && dataBean.length > 0) {
					List<SchoolData> schools = schoolDataDao.findAll();
					Map<String,SchoolData> oldMaps = new HashMap<String, SchoolData>();
					for(SchoolData data : schools) {
						oldMaps.put(data.getId().toString(), data);
					}
					Map<String,SchoolDataBean> newMaps = new HashMap<String,SchoolDataBean>();
					for(SchoolDataBean userBean : dataBean){
						SchoolData tempData = oldMaps.get(String.valueOf(userBean.getSchoolid()));
						if(tempData == null) {
							tempData = new SchoolData();
							tempData.setId(userBean.getSchoolid());
							tempData.setName(userBean.getName());
							tempData.setRegionalCode(userBean.getRegionalcode());
							schoolDataDao.create(tempData);
						}else{
							newMaps.put(String.valueOf(userBean.getSchoolid()), userBean);
						}
						
					}
					for(SchoolData data : schools) {
						SchoolDataBean tempBean = newMaps.get(data.getId().toString());
						if(tempBean != null){
							if(data.getName() != tempBean.getName() || data.getRegionalCode() != tempBean.getRegionalcode()) {
								data.setName(tempBean.getName());
								data.setRegionalCode(tempBean.getRegionalcode());
								this.updateSchoolData(data);
							}
						} else {
							this.deleteSchoolData(data.getId());
						}
					}
				}
			}

		} catch (AxisFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
